package org.arain.baseii.system.gen;

import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;
import org.arain.baseii.common.CommonServiceImpl;
import org.arain.baseii.grid.GridData;
import org.arain.baseii.grid.QueryParam;
import org.arain.baseii.mapper.SysGeneratorMapper;
import org.arain.baseii.utils.GenUtils;
import org.arain.baseii.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Service
public class GenServiceImpl extends CommonServiceImpl<GenDto> implements GenService{
	@Autowired
	private SysGeneratorMapper sysGeneratorMapper;
	@Override
	public String load_grid(QueryParam param) {
		GenDto dto = new GenDto();
		try {
			dto = this.jsonToObject(param.getFilterRules(), dto);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<>();
		map.put("offset", param.getPage());
		map.put("limit", param.getRows());
		map.put("tableName", dto.getTableName());
		map.put("orderByClause", param.getSort()+" "+param.getOrder());
		
		JSONArray array = new JSONArray();
		
		int total = sysGeneratorMapper.queryTotal(map);
		GridData data = new GridData();
		List<Map<String,Object>> list = sysGeneratorMapper.queryList(map);
		for (Map<String, Object> map2 : list) {
			JSONObject object = new JSONObject();
			object.put("tableName", map2.get("tableName"));
			object.put("engine", map2.get("engine"));
			object.put("tableComment", map2.get("tableComment"));
			object.put("createTime", TimeUtil.format((Date) map2.get("createTime")));
			
			array.add(object);
		}
		data.setTotal(total);
		data.setRows(array);
		return GridData.gridToJson(data);
	}
	
	@Override
	public Map<String, String> queryTable(String tableName) {
		return sysGeneratorMapper.queryTable(tableName);
	}

	@Override
	public List<Map<String, String>> queryColumns(String tableName) {
		return sysGeneratorMapper.queryColumns(tableName);
	}
	
	
	@Override
	public byte[] generatorCode(String[] tableNames, String author, String mapper, String page){
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);
		
		for(String tableName : tableNames){
			//查询表信息
			Map<String, String> table = queryTable(tableName);
			//查询列信息
			List<Map<String, String>> columns = queryColumns(tableName);
			//生成代码
			GenUtils.generatorCode(table, columns, zip,author,mapper,page);
		}
		IOUtils.closeQuietly(zip);
		return outputStream.toByteArray();
	}

}
